package activity.main;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.laoxinwen.app.R;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengDialogButtonListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import activity.ProfileActivity;
import activity.SearchActivity;
import activity.SettingsActivity;
import activity.collection.FavoriteActivity;
import bean.MainNewsTab;
import bean.wraper.NewsTabMapWrapper;
import common.Constants;
import common.HttpCallBack;
import common.MyApp;
import common.MyTheme;
import common.Requester;
import common.ServerConfig;
import common.UserConfig;
import share.LoginHelper;
import share.LoginType;
import share.ShareActivity;
import share.ShareDialog;
import util.IntentUtil;
import util.NetUtil;
import util.ToastUtil;
import util.bitmap.FileUtil;
import util.bitmap.Img;
import view.MainTopTabContainer;
import view.SlidingFrameQQ;


public class MainActivity extends ShareActivity implements SlidingFrameQQ.SlidingStateListener, LoginHelper.LoginResultListener, MainTopTabContainer.OnTopTabSelectHandler {
    public static final String ACTION_OPEN_MENU = "open menu";

    @id(R.id.iv_loading)
    private ProgressBar ivloading;
    private long lastBackPressed;
    private LoginHelper loginHelper;

    private int[] selectTabIndices = new int[]{0, 0, 0};
    private int selectMainTabGroup = 0;
    private List<MainNewsTab[]> tabList;
    private List<HashMap<String, BaseFrgList>> frgList = new ArrayList<>();

    @id(R.id.main_root)
    private ViewGroup rootView;

    @id(R.id.bt_article)
    private View vTabArticle;
    @id(R.id.bt_news)
    private View vTabNews;
    @id(R.id.bt_topic)
    private View vTabTopic;

    @id(R.id.news_viewpager)
    private ViewPager newsViewPager;
    @id(R.id.article_viewpager)
    private ViewPager articleViewPager;
    @id(R.id.topic_viewpager)
    private ViewPager topicViewPager;
    @id(R.id.top_tab_container)
    private MainTopTabContainer topTabContainer;

    @id(R.id.slidingFrame)
    private SlidingFrameQQ slidingFrameQQ;
    @id(R.id.user_avatar)
    private ImageView userAvatar;
    @id(R.id.user_name)
    private TextView userNameText;

    @id(R.id.menu_night_img)
    private View nightModeImg;
    @id(R.id.menu_night_text)
    private TextView nightModeText;

    private Dialog shareDialog;

    public static void jumpHereForLogin(Context context) {
        Intent it = new Intent(context, MainActivity.class);
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        it.setAction(ACTION_OPEN_MENU);
        context.startActivity(it);
    }

    //
    //友盟检测更新
    //
    private void checkUpdate() {
        UmengUpdateAgent.update(this);
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            String channel = appInfo.metaData.getString("UMENG_CHANNEL");
            UmengUpdateAgent.setChannel(channel);
        } catch (Exception e) {
        }
        UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
            @Override
            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                switch (updateStatus) {
                    case UpdateStatus.Yes: // has update
                        UmengUpdateAgent.setDeltaUpdate(false);//尝试进行增量更新
                        UmengUpdateAgent.showUpdateDialog(MainActivity.this, updateInfo);
                        break;
                }
            }
        });
        UmengUpdateAgent.setDialogListener(new UmengDialogButtonListener() {
            @Override
            public void onClick(int status) {
                if (UpdateStatus.Update == status) {
                    ToastUtil.showToast(MainActivity.this, "开始下载", Toast.LENGTH_SHORT);
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loadView();
        slidingFrameQQ.setLeftBound(70);
        slidingFrameQQ.setAnimationDuration(800);
        slidingFrameQQ.setSlidingStateListener(this);
        slidingFrameQQ.setSlideFromEdge(true);
        setMenu();
        loginHelper = new LoginHelper(this);
        loginHelper.setLoginResultListener(this);
        if (savedInstanceState != null) {
            selectMainTabGroup = savedInstanceState.getInt("tabgroup");
            selectTabIndices = savedInstanceState.getIntArray("tab");
        }
        setSelectedMainTabGroup(selectMainTabGroup);

        checkUpdate();
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                requestTabList();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setMenu();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tabgroup", selectMainTabGroup);
        outState.putIntArray("tab", selectTabIndices);
    }

    @Override
    public void onBackPressed() {
        if (slidingFrameQQ.isLeftMenuOpened()) {
            slidingFrameQQ.closeMenu();
        } else {
            if (System.currentTimeMillis() - lastBackPressed < 2000) {
                finish();
            } else {
                lastBackPressed = System.currentTimeMillis();
                showToast("再次点击退出应用");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_name:
            case R.id.user_avatar:
                if (!UserConfig.isLogined()) {
                    showLoginDialog();
                } else {
                    startActivity(new Intent(this, ProfileActivity.class));
                }
                break;
            case R.id.bt_search:
                startActivity(new Intent(this, SearchActivity.class));
                break;
            case R.id.bt_menu:
                slidingFrameQQ.openMenu();
                break;
            case R.id.menu_setting:
                startActivity(new Intent(this, SettingsActivity.class));
                break;
            case R.id.menu_favorite:
                if (!UserConfig.isLogined()) {
                    showLoginDialog();
                } else {
                    slidingFrameQQ.closeMenu();
                    startActivity(new Intent(this, FavoriteActivity.class));
                }
                //                bindQq();
                //TODO
                break;
            case R.id.menu_score_on_market:
                try {
                    startActivity(IntentUtil.getIntentForMarketScore(this));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.menu_suggest_to_us:
                FeedbackAgent agent = new FeedbackAgent(this);
                agent.startFeedbackActivity();
                //                startActivity(new Intent(MainActivity.this, Feedback.class));
                break;
            case R.id.menu_remommend_to_friend:
                shareApp();
                break;
            case R.id.menu_night:
                UserConfig.setNightMode(!UserConfig.isNightMode());
                setMenu();
                MyApp.switchTheme(UserConfig.isNightMode() ? MyTheme.THEME_NIGHT : UserConfig.getMainTheme());
                restartSelf();
                break;
            case R.id.bt_news:
                setSelectedMainTabGroup(0);
                break;
            case R.id.bt_article:
                setSelectedMainTabGroup(1);
                break;
            case R.id.bt_topic:
                setSelectedMainTabGroup(2);
                break;
        }
    }

    private void setSelectedMainTabGroup(int group) {
        selectMainTabGroup = group;
        View[] groupTabs = {vTabNews, vTabArticle, vTabTopic};
        ViewPager[] viewPagers = {newsViewPager, articleViewPager, topicViewPager};
        for (View groupTab : groupTabs) {
            groupTab.setSelected(false);
        }
        for (ViewPager viewPager : viewPagers) {
            viewPager.setVisibility(View.GONE);
        }
        groupTabs[group].setSelected(true);
        viewPagers[group].setVisibility(View.VISIBLE);
        if (tabList != null && !tabList.isEmpty()) {
            refreshGroupTabs(group);
        }
    }

    private void refreshGroupTabs(final int group) {
        topTabContainer.setTabs(tabList.get(group));
        topTabContainer.selectTab(tabList.get(group)[selectTabIndices[group]]);
        //检查是否需要刷新
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                BaseFrgList frg = frgList.get(group).get(String.valueOf(selectTabIndices[group]));
                if (frg != null) {
                    frg.checkFresh();
                }
            }
        });
    }

    //
    //viewpager相关
    //
    private void requestTabList() {
//        Log.i("whatfuck", "request tablist");
        showLoading();
        Requester.getNewsTabList(new HttpCallBack<NewsTabMapWrapper>() {
            @Override
            protected void onNetError() {
                showToast(Constants.MSG_NET_ERROR);
                cancelLoading();
                registerConnectReceiver();
            }

            @Override
            protected void onServerError(NewsTabMapWrapper data) {
                super.onServerError(data);
                cancelLoading();
            }

            @Override
            public void onSucceed(NewsTabMapWrapper data) {
                tabList = data.getData();
                setModuleNewsList();
                cancelLoading();
            }
        });
    }

    private PagerAdapter generatePageAdapter(final int mainTabGroup) {
        //FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        FragmentStatePagerAdapter adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                MainNewsTab tab = tabList.get(mainTabGroup)[position];
                switch (mainTabGroup) {
                    case 0:
                        if(tab.isGrpshow()) {
                            return new FrgIndexList();
                        }
                        return new FrgNewsList();
                    case 1:
                        if(tab.isGrpshow()) {
                            return new FrgIndexList();
                        }
                        return new FrgArticleList();
                    default:
                        return new FrgTopicList();
                }
            }

            @Override
            public int getCount() {
                return tabList.get(mainTabGroup).length;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                BaseFrgList fragment = (BaseFrgList) super.instantiateItem(container, position);
                frgList.get(mainTabGroup).put(String.valueOf(position), fragment);

                Bundle bundle = new Bundle();
                MainNewsTab tab = tabList.get(mainTabGroup)[position];
                bundle.putInt("tab", tab.getId());
                bundle.putBoolean("onepage", tab.isOnepage());
                bundle.putInt("main", mainTabGroup);
                bundle.putString("title", tab.getTitle());
                fragment.setBundle(bundle);
                return fragment;
            }
        };
        return adapter;
    }

    private ViewPager.OnPageChangeListener generatePageChangeListener(final int mainTabGroup) {
        ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int state) {
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(final int position) {
                MainNewsTab tab = tabList.get(mainTabGroup)[position];
                topTabContainer.selectTab(tab);
                selectTabIndices[selectMainTabGroup] = position;
                //检查是否需要刷新
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        frgList.get(mainTabGroup).get(String.valueOf(position)).checkFresh();
                    }
                });
            }
        };
        return pageChangeListener;
    }

    private void setModuleNewsList() {
        ViewPager[] viewpagers = {newsViewPager, articleViewPager, topicViewPager};
        PagerAdapter[] adapters = {generatePageAdapter(0), generatePageAdapter(1), generatePageAdapter(2)};
        ViewPager.OnPageChangeListener[] listeners = {generatePageChangeListener(0), generatePageChangeListener(1), generatePageChangeListener(2)};
        frgList.clear();
        for (int i = 0; i < tabList.size(); i++) {
            frgList.add(new HashMap<String, BaseFrgList>());
        }
        for (int i = 0; i < viewpagers.length; i++) {
            viewpagers[i].setOffscreenPageLimit(1);
            viewpagers[i].setAdapter(adapters[i]);
            viewpagers[i].setOnPageChangeListener(listeners[i]);
        }
        //渲染tab
        refreshGroupTabs(selectMainTabGroup);
    }

    @Override
    public void onSelectTopTab(MainNewsTab tab, int index) {
        ViewPager[] viewpagers = {newsViewPager, articleViewPager, topicViewPager};
        viewpagers[selectMainTabGroup].setCurrentItem(index);
    }

    //
    //网络变好时自动加载列表
    //
    private void registerConnectReceiver() {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(myNetReceiver, mFilter);
    }

    private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (NetUtil.isNetworkConnected(MainActivity.this)) {
                requestTabList();
                unregisterReceiver(myNetReceiver);
            }
        }
    };

    //加载标志
    private void showLoading() {
        ivloading.setVisibility(View.VISIBLE);
    }

    private void cancelLoading() {
        ivloading.setVisibility(View.GONE);
    }

    //
    //左侧菜单相关
    //
    private void setMenu() {
        if (UserConfig.isLogined()) {
            userNameText.setText(UserConfig.getUserInfo().getName());
            final Img img = new Img(FileUtil.getCacheDir(), FileUtil.getFileDir(), UserConfig.getUserInfo().getAvatar());
            img.setRadius(100);
            img.downloadAndDecodeAsync(new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    userAvatar.setImageBitmap(img.getBitmap());
                }
            });
        } else {
            userNameText.setText("立即登录");
            userAvatar.setImageResource(R.drawable.icon_default);
        }
        nightModeImg.setSelected(UserConfig.isNightMode());
        if (UserConfig.isNightMode()) {
            nightModeText.setText("日间模式");
        } else {
            nightModeText.setText("夜间模式");
        }
    }

    @Override
    public void onMenuClose() {
        MobclickAgent.onPageEnd("菜单页");
    }

    @Override
    public void onMenuOpen() {
        MobclickAgent.onPageStart("菜单页");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (ACTION_OPEN_MENU.equals(intent.getAction())) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    slidingFrameQQ.openMenu();
                }
            }, 500);
        }
    }

    @Override
    public void onCenterViewClickWhenMenuOpenedIdle() {
        slidingFrameQQ.closeMenu();
    }

    //登录相关
    private void showLoginDialog() {
        loginHelper.showDialog();
    }

    @Override
    protected void onWechatInfoObtain() {
        loginHelper.login(LoginType.WECHAT);
    }

    @Override
    protected void onWeiboInfoObtained() {
        loginHelper.login(LoginType.SINA);
    }


    @Override
    protected void onQqInfoObtained() {
        loginHelper.login(LoginType.QQ);
    }

    @Override
    public void onLoginFail() {
        loginHelper.dismissDialog();
    }

    @Override
    public void onLoginSucceed() {
        setMenu();
        loginHelper.dismissDialog();
    }

    //推荐给好友
    private void shareApp() {
        shareDialog = ShareDialog.getShareDialog(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dismiss();

                String title = "新闻还可以这样看？";
                String summary = "每一篇新闻都不是孤立的，强烈推荐个新闻APP，一定要看哦！";
                String srcUrl = ServerConfig.SERVER_HOST + "/download";
                String imgUrl = ServerConfig.DEFAULT_SHARE_IMG;
                switch (v.getId()) {
                    case R.id.share_qq:
                        shareToQq(title, summary, imgUrl, srcUrl);
                        break;
                    case R.id.share_qq_zone:
                        shareToQqZone(title, summary, imgUrl, srcUrl);
                        break;
                    case R.id.share_weibo:
                        shareToWeibo(title, summary, imgUrl, srcUrl);
                        break;
                    case R.id.share_weixin:
                        shareToWeixin(title, summary, imgUrl, srcUrl);
                        break;
                    case R.id.share_weixin_friends:
                        shareToWeixinFriendCircle(title, summary, imgUrl, srcUrl);
                        break;
                    case R.id.share_url:
                        shareCopyUrl(srcUrl);
                        break;
                }
            }
        });
        shareDialog.show();
    }

    public ViewGroup getRootView() {
        return rootView;
    }
}
